package com.fastloan.mgt.application.base.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fastloan.mgt.application.base.model.ApplicationVo;
import com.fastloan.mgt.application.base.service.ApplicationService;
import com.fastloan.mgt.application.base.service.BackgroundApplicationService;
import com.fastloan.mgt.application.base.service.impl.third.ThirdApplication;
import com.fastloan.mgt.processcontrol.base.util.BeanFactoryUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Optional;

import static com.fastloan.core.apiauth.service.EncryptUtil.AGENT_ID;

/**
 * 后台进件实现类
 *
 * @author yanwe
 * createTime 2018-01-2018/1/11 10:20
 */
@Service
public class BackgroundApplicationServiceImpl implements BackgroundApplicationService {

    private static final Logger logger = LoggerFactory.getLogger(BackgroundApplicationServiceImpl.class);

    @Autowired
    private ApplicationService applicationService;

    @Override
    public void submitApplication(Object object){
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(object));
        String agentId = jsonObject.getString(AGENT_ID);
        Map<String, ThirdApplication> thirdApplicationMap = BeanFactoryUtil.getBeansOfType(ThirdApplication.class);
        Optional<ThirdApplication> thirdApplicationOptional = thirdApplicationMap.values().stream()
                .filter(thirdApplication -> thirdApplication.getAgentId().equals(agentId))
                .findFirst();
        if (!thirdApplicationOptional.isPresent()){
            logger.warn("未知的机构编号:"+agentId+",无法申请进件！");
            return;
        }
        ApplicationVo applicationVo = thirdApplicationOptional.get().processApplication(object);
        applicationService.submitApplication(applicationVo);
    }
}
